package com.orderplus.opshop.synces.template;

import com.orderplus.opshop.common.util.RequestLogUtils;
import com.orderplus.opshop.core.constants.enums.ResponseCodeConstant;
import com.orderplus.opshop.core.data.request.RequestParam;
import com.orderplus.opshop.core.data.response.ResponseData;
import com.orderplus.opshop.core.exception.CommonException;
import com.orderplus.opshop.core.exception.ParamErrorException;
import com.orderplus.opshop.synces.service.elasticsearch.data.QueryParamData;
import com.orderplus.opshop.synces.service.elasticsearch.data.QueryResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.dao.DuplicateKeyException;

import javax.validation.ConstraintViolationException;

/**
 * es分页查询模板
 **/
@Slf4j
public abstract class EsPageTemplate {
	/**
	 * 外层call
	 *
	 * @param request
	 * @return
	 */
	public ResponseData<QueryResultData.ListQueryResultData> call(RequestParam<QueryParamData> request) {
		ResponseData<QueryResultData.ListQueryResultData> response = new ResponseData<>();
		try {
//			if (!StringUtils.isEmpty(ApplicationContext.getContainer().getApplicationName())) {
//				request.setAppName(ApplicationContext.getContainer().getApplicationName());
//			}
			request.setTraceId(RequestLogUtils.getCurTraceId(request));
			request.setOperLevel(RequestLogUtils.getCurOperLevel(request));
			//请求remote
			QueryResultData.ListQueryResultData result = callInner(request);
			response.setData(result);
			response.setCode(ResponseCodeConstant.SUCCESS.getResponseCode());
			response.setMsg(ResponseCodeConstant.SUCCESS.getResponseDesc());
		} catch (ConstraintViolationException e) {
			ConstraintViolationException cvException = (ConstraintViolationException) e;
			response.setCode(ResponseCodeConstant.REQUEST_ILLEGAL.getResponseCode());
			response.setMsg(ExceptionUtils.getMessage(cvException));
		} catch (ParamErrorException e) {
			response.setCode(e.getCode());
			response.setMsg(e.getMessage());
		} catch (CommonException e) {
			response.setCode(e.getCode());
			response.setMsg(e.getMessage());
		} catch (DuplicateKeyException e) {
			log.error("DuplicateKeyException错误,类:[{}],异常:", this.getClass().getName(), e);
			response.setCode(ResponseCodeConstant.DB_EXCEPTION.getResponseCode());
			response.setMsg("存在不可重复数据:" + e.getCause().getMessage());
		} catch (Exception e) {
			log.error("Exception错误,类:[{}],异常:", this.getClass().getName(), e);
			response.setCode(ResponseCodeConstant.SYS_EXCEPTION.getResponseCode());
			response.setMsg(ResponseCodeConstant.SYS_EXCEPTION.getResponseDesc());
		}
		return response;
	}

	protected abstract QueryResultData.ListQueryResultData callInner(RequestParam<QueryParamData> request) throws Exception;

}
